<template>
	<!-- 部门树形结构对话框	 -->
	<el-dialog title="部门选择框" :visible.sync="isEditable" :center="true" width="50%" @open="opendDialog" @close="closeDialog" :close-on-click-modal="false" :default-expand-all="true" append-to-body>
		
		<!-- 懒加载模式 -->
		<!-- <el-tree v-show="!deptCheck" :data="treeData" ref="tree" node-key="deptId" :props="defaultProps" :load="loadDept" :check-strictly="treeOptions.checkStrictly" lazy show-checkbox @check-change="onlyOneChecked"></el-tree> -->
		
		<!-- 直接加载模式 -->
		<el-tree v-show="!deptCheck" :data="treeData" ref="tree" node-key="deptId" :props="defaultProps" :check-strictly="treeOptions.checkStrictly" show-checkbox @check-change="onlyOneChecked"></el-tree>

		<!-- 所有部门 -->
		<div style="margin-top:10px;">
			<el-checkbox v-model="deptCheck">所有部门</el-checkbox>
			<el-button type="success" size="mini" v-show="showContainer" @click="selectedSubDept">包含下级部门</el-button>
		</div>
		<!-- 所有部门 End -->

		<!-- 对话框底部工具栏 -->
		<span slot="footer" class="dialog-footer">
			<el-button type="info" @click="cancelEdit">取消</el-button>
			<el-button type="primary" @click="finishedEdit">确定</el-button>
		</span>
		<!-- 对话框底部工具栏 End-->
	</el-dialog>
</template>

<script>
	export default{
		// 部门树形组件
		name: 'departmentTreeDlg',
		// options: {checkStrictly: boolean, onlyOneChecked: boolean} 配置项
		props: ['isShowType', 'deptMessage', 'checkAllType', 'options'],
		data(){
			return {
				// 启用编辑
				isEditable: this.isShowType,
				// 初始化信息
				initMessage: this.deptMessage,
				// 树形结构配置项
				treeOptions: {
					checkStrictly: this.options ? this.options.checkStrictly : true,
					onlyOneChecked: this.options ? this.options.onlyOneChecked : false
				},

				// 显示子部门选择框
				showContainer: this.options ? this.options.showContainer : true,

				// 全选状态
				deptCheck: this.checkAllType,

				// 树形属性
				defaultProps: {
					label: 'deptName',
					children: 'childrenList'
				},

				// 已选项
				selectedTree: [],

				// 所选部门id
				deptId: '',
				// 所选部门标签
				deptLabel: '',

				// 树形表格数据
				treeData: [],
			}
		},
		mounted: function(){
			this.reset();
			this.loadDeptData();
		},
		methods: {
			// 状态重置
			reset: function(){
				this.deptId = '';
				this.deptLabel = '';
				this.deptCheck = false;
			},
			/**
			 * [加载部门节点]
			 * @param  {[object]} node    [节点对象]
			 * @param  {[function]} resolve [解析函数]
			 */
			loadDept: function(node, resolve){
				// 请求部门数据
				this.$http.post('/api/tree/dept', {level: node.level, supDeptId: node.data.deptId?node.data.deptId:0}, {emulateJSON: true}).then(response => {
					console.log("node: ", node);
					var treeData = response.data || [];
					// 解析渲染数据
					resolve(treeData);

					// 设置已选择数据
					this.$refs.tree.setCheckedKeys(this.selectedTree);

				}, response => {
					console.log('Ajax can not get the data from the server!!!');
				});
			},
			/**
			 * 加载所有部门数据
			 * @return {[type]} [description]
			 */
			loadDeptData: function(){
				// 请求部门数据
				this.$http.post('/api/tree/deptData', {emulateJSON: true}).then(response => {
					this.treeData = response.data || [];
				}, response => {
					console.log('Ajax can not get the data from the server!!!');
				});
			},

			// 打开对话框回调函数
			opendDialog: function(){
				// 初始化已选项
				this.selectedTree = this.selectedTree.concat(this.initMessage.split(','));
				this.$refs.tree && this.$refs.tree.setCheckedKeys(this.selectedTree);
			},
			// 关闭对话框回调函数
			closeDialog: function(){
				this.deptId = '';
				this.deptLabel = ''; 
				this.selectedTree = [];
				this.$refs.tree.setCheckedKeys([]);
			},

			// 取消编辑
			cancelEdit: function(){
				// 重置状态
				this.reset();
				this.isEditable = false;
			},
			// 完成编辑
			finishedEdit: function(){
				// 部门Id拼接串
				this.deptId = this.$refs.tree.getCheckedKeys().join(',');
				// 所选部门标签
				var deptArray = this.$refs.tree.getCheckedNodes();
				var deptLabelArray = [];
				for (let i = 0; i <= deptArray.length - 1; i++){
					deptLabelArray.push(deptArray[i].deptName);
				}
				this.deptLabel = deptLabelArray.join(',');
				// 全部部门
				this.deptLabel = this.deptCheck ? '所有部门' : this.deptLabel;
				this.deptId = this.deptCheck ? '' : this.deptId;
				// 向父组件传值
				this.$emit('message', this.deptLabel, this.deptId, this.deptCheck);
				// 重置状态
				this.reset();
				// 关闭对话框
				this.isEditable = false;
			},
			/* 对话框操作 End*/

			// 树形单选控制
			onlyOneChecked: function(obj, isChecked, children){
				if (this.treeOptions.onlyOneChecked && isChecked){
					this.$refs.tree.setCheckedKeys([obj.deptId]);
				}

				// 缓存已选择项
				this.selectedTree = this.$refs.tree.getCheckedKeys().concat(this.initMessage.split(','));
			},

			// 包含所有子部门
			selectedSubDept: function(){
				var deptArray = this.$refs.tree.getCheckedNodes();
				var nodes = [];
				for (let i = 0; i <= deptArray.length - 1; i++){
					nodes.push(deptArray[i].deptId);
					this.getSubDeptIds(deptArray[i], nodes);
				}
				this.$refs.tree.setCheckedKeys(nodes);
			},
			// 获得所有子部门id
			getSubDeptIds: function(depts, nodes){
				let dept = depts.childrenList;
				let len = dept ? dept.length : 0;
				let i = 0;
				while (i < len){
					if (dept[i].childrenList){
						this.getSubDeptIds(dept[i], nodes);
					} 
					nodes.push(dept[i].deptId);
					i++;
				}
			}
		},
		watch: {
			// 监听父组件isShowType状态
			'isShowType': function(value){
				this.isEditable = value;
			},
			// 监听父组件deptMessage状态
			'deptMessage': function(value){
				this.initMessage = value;
			},
			// 监听父组件deptMessage状态
			'checkAllType': function(value){
				this.deptCheck = value;
			},
			// 监听子组件isEditable状态
			'isEditable': function(value){
				this.$emit('update:isShowType', value);
			}
		}
	}
</script>
